import http from './interface'
import {
	config,
	AUTHORIZATION
} from '../config.js'
import cache from '@/common/cache.js'
import tools from '@/common/tools.js'
const $config = {
	fileDomain: config.fileDomain,
	bmsURL: config.bmsURL,
	authURL: config.authURL
}

const X_MENU_ID = cache.key.X_MENU_ID
const X_VISIT_CODE = cache.key.X_VISIT_CODE
const VERSION = cache.key.VERSION

function $api({
	url,
	data,
	method,
	header
}) {
	if(method === 'post'){
		uni.showNavigationBarLoading()
	}
	//设置请求前拦截器
	http.interceptor.request = (config) => {
		config.timeout = 15000
		// Token
		const token = cache.get(AUTHORIZATION)
		if (token) {
			config.header[AUTHORIZATION] = token
		} else {
			delete config.header[AUTHORIZATION]
		}
		// 页面id
		const menuId = cache.get(X_MENU_ID)
		if (menuId) {
			config.header[X_MENU_ID] = menuId
		} else {
			delete config.header[X_MENU_ID]
		}
		// 唯一访问码
		const visitCode = cache.get(X_VISIT_CODE)
		if (visitCode) {
			config.header[X_VISIT_CODE] = visitCode
		} else {
			delete config.header[X_VISIT_CODE]
		}
		// 版本号
		const version = cache.get(VERSION)
		if (version) {
			config.header[VERSION] = version
		} else {
			delete config.header[VERSION]
		}
	}

	//设置请求结束后拦截器
	http.interceptor.response = (response) => {
		if (method === 'post') {
			uni.hideNavigationBarLoading()
		}
		if ('request:fail abort' == response['errMsg'] || response['statusCode'] == 500) {
			uni.showToast({
				title: '服务异常:' + response['statusCode'],
				icon: 'none'
			})
		}
		const data = response.data || {}
		console.log(data)
		if (data.code != 1) {
			if (data.code == 2010) {
				uni.showModal({
					title:'提示',
					content: '当前用户未登录，请前往登录',
					confirmText:'去登录',
					confirmColor:'#287FFA',
					success(res){
						if(res.confirm){
							uni.removeStorageSync(AUTHORIZATION)
							// 获取加载的页面
							const pages = getCurrentPages()
							// 获取当前页面的对象
							const currentPage = pages[pages.length - 1]
							// 当前页面url
							const url = currentPage.route
							if(url.indexOf('login/login') < 0){
								cache.put(cache.key.router, `/${url}`)
								// 如果要获取url中所带的参数可以查看options
								const options = currentPage.options
								// 参数多时通过&拼接url的参数
								let args = ''
								for (const key in options) {
									args += '&' + key + '=' + options[key]
								}
								if (args) {
									url += '?' + args
								}
								cache.put(cache.key.url, `/${url}`)
								uni.reLaunch({
									url:'/pages/login/login'
								})
							}
						}
					}
				})
			} else {
				uni.showToast({
					title: data.msg || data.data,
					icon: 'none'
				})
			}
		} else {
			// 判断返回状态 执行相应操作
			return data;
		}
	}
	return http.request({
		url: url,
		data: data,
		method: method || 'get',
		header: header || {}
	})
}

export {
	$api,
	$config
}
